package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.elm.model.Food;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.elm.service.BusinessService;
import cn.edu.tju.elm.service.FoodService;
import cn.edu.tju.core.security.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/foods")
@Tag(name = "管理商品")
public class FoodController {
    @Autowired
    private UserService userService;

    @Autowired
    private FoodService foodService;

    @Autowired
    private BusinessService businessService;

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取商品详情", method = "GET")
    public HttpResult<Food> getFoodById(@PathVariable Long id){
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        Optional<Food> foodOptional = foodService.findById(id);

        if (foodOptional.isPresent()) {
            return HttpResult.success(foodOptional.get());
        } else {
            return HttpResult.failure(ResultCodeEnum.FOOD_NOT_FOUND);
        }
    }

    @GetMapping("")
    @Operation(summary = "获取商品列表", description = "获取所有商品列表")
    public HttpResult<List<Food>> getAllFoods(@RequestParam(name = "business", required = false) Long businessId,
                                              @RequestParam(name = "order", required = false) Long orderId){
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        List<Food> foods;

        if (businessId != null) {
            // 按商家筛选
            foods = foodService.findByBusinessId(businessId);
        } else {
            // 获取所有商品
            foods = foodService.findAll();
        }

        return HttpResult.success(foods);
    }

    @PostMapping("")
    @Operation(summary = "新增商品", description = "商家为自己的店铺创建新的商品")
    public HttpResult<Food> addFood(@RequestBody Food food){
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        try {
            // 检查传入的店铺信息是否存在
            if (food.getBusiness() == null || food.getBusiness().getId() == null) {
                return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND, "店铺信息不能为空");
            }

            // 查询店铺详细信息
            Optional<Business> businessOptional = businessService.findById(food.getBusiness().getId());
            if (!businessOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND, "店铺不存在");
            }

            Business business = businessOptional.get();

            // 权限检查：商家只能给自己的店铺添加商品，管理员可以给任何店铺添加商品
            boolean isAdmin = currentUser.getAuthorities().stream()
                    .anyMatch(auth -> "ADMIN".equals(auth.getName()));
            boolean isOwner = business.getBusinessOwner().getId().equals(currentUser.getId());

            if (!isAdmin && !isOwner) {
                return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED_OPERATION, "无权为此店铺添加商品");
            }

            // 设置正确的店铺信息（使用从数据库查询的完整信息）
            food.setBusiness(business);

            // 设置创建时间和更新时间
            LocalDateTime now = LocalDateTime.now();
            food.setCreateTime(now);
            food.setUpdateTime(now);

            // 设置创建者和更新者
            food.setCreator(currentUser.getId());
            food.setUpdater(currentUser.getId());

            // 设置删除状态
            food.setDeleted(false);

            // 保存商品
            Food savedFood = foodService.save(food);
            return HttpResult.success(savedFood);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }



    @PatchMapping("/{id}")
    @Operation(summary = "修改商品的信息", description = "修改商品信息（某商家自己的）")
    public HttpResult<Food> updateFood(@PathVariable Long id, @RequestBody Food food){
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities().orElse(null);

            // 检查是否是管理员
            boolean isAdmin = currentUser.getAuthorities().stream()
                    .anyMatch(authority -> "ADMIN".equals(authority.getName()));

            // 获取要修改的商品信息
            Optional<Food> existingFoodOptional = foodService.findById(id);
            if (existingFoodOptional.isEmpty()) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商品不存在");
            }

            Food existingFood = existingFoodOptional.get();

            // 检查当前用户是否是商家的所有者
            boolean isBusinessOwner = false;
            if (!isAdmin && existingFood.getBusiness() != null) {
                Optional<Business> businessOptional = businessService.findById(existingFood.getBusiness().getId());
                if (businessOptional.isPresent()) {
                    Business business = businessOptional.get();
                    isBusinessOwner = business.getBusinessOwner().getId().equals(currentUser.getId());
                }
            }

            // 权限检查：只有管理员或商家所有者可以修改商品
            if (!isAdmin && !isBusinessOwner) {
                return HttpResult.failure(ResultCodeEnum.FORBIDDEN, "无权修改该商品");
            }

            // 防止修改商家归属（如果请求中包含了business信息）
            if (food.getBusiness() != null && !food.getBusiness().getId().equals(existingFood.getBusiness().getId())) {
                return HttpResult.failure(ResultCodeEnum.FORBIDDEN, "不能修改商品的所属商家");
            }

            // 设置ID确保更新的是正确的商品
            food.setId(id);

            // 保留原有的商家信息（防止被覆盖）
            if (food.getBusiness() == null) {
                food.setBusiness(existingFood.getBusiness());
            }

            // 调用Service层保存
            Food updatedFood = foodService.save(food);
            return HttpResult.success(updatedFood);

        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "修改商品信息失败: " + e.getMessage());
        }
    }
}